# coding=utf-8
# dn-刘忙(QQ:734523893)

# 1.文件名称:use.txt
#    创建该文件,路径由你自己指定,打开该文件,往里面写入
#    str_content = ['tom is boy','\n','you are cool','\n','今天你怎么还不回来']
#    把数据写入到该文件中,注意操作的模式,关闭文件句柄后
#    再次打开该文件句柄,然后读取文件中内容,用with代码块
#    实现,然后打印输出信息到控制台,注意换行符

str_content = ['tom is boy', '\n', 'you are cool', '\n', '今天你怎么还不回来']

with open('tom.txt','w',encoding='utf-8') as f:
    for i in str_content:
        f.write(i)
with open('tom.txt','r',encoding='utf-8') as f:
    print(f.read())


# 2.with创建一个文件homework.txt,尝试多种操作模式.进行写读操作,注意区别

with open('homework.txt','w', encoding='gbk') as f:
    f.write('动脑学院')
with open('homework.txt','r+', encoding='gbk') as f:
    print(f.read())

with open('homework.txt', 'w+', encoding='gbk') as f:
    f.write('dn_学院')
    f.flush()
    f.seek(0)
    print(f.read())

with open('homework.txt', 'r+', encoding='gbk') as f:
    f.write('dn_学院1')
    f.write('\ndn_学院2')
    f.flush()
    f.seek(0)
    print(f.read())

# 3.理解文件句柄, 对比read(), readline(), readlines()写一个小例子
str_content = ['tom is boy', '\n', 'you are cool', '\n', '今天你怎么还不回来']

with open('home1.txt','w',encoding='utf-8') as f:
    for i in str_content:
        f.write(i)

with open('home1.txt','r',encoding='utf-8') as f:
    print(f.read())
    print(type(f.read()))    #读取文件的全部，返回字符串

with open('home1.txt','r',encoding='utf-8') as f:
    print(f.readline())     #只读取一行，返回字符串
    print(type(f.readline()))

with open('home1.txt','r',encoding='utf-8') as f:
    print(f.readlines())      #读取全部内容,返回是列表


# 4.准备一张jpg图片, 把图片中数据读书出来, 并写入到文件my_img.jpg文件中,
# 操作完毕后尝试打开my_img.jpg文件看

with open('E:\PythonSofts\PyProject\picture\mirror.jpg', 'rb+') as f:
    content = f.read()
    print(type(content))
with open('my_img.jpg', 'wb+') as f:
    f.write(content)

